package com.pms.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.entity.IotAgency;
import com.pms.entity.IotWaterPumpGroup;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.mapper.IotAgencyMapper;
import com.pms.mapper.IotWaterPumpGroupMapper;
import com.pms.service.IIotAgencyService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pms.service.IIotEqCameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author asus
 * @since 2018-07-18
 */
@Service
public class IotAgencyServiceImpl extends ServiceImpl<IotAgencyMapper, IotAgency> implements IIotAgencyService {

    @Autowired
    IotWaterPumpGroupMapper waterPumpGroupMapper;
    @Autowired
    IIotEqCameraService iotEqCameraService;// 删水泵房 删除摄像头
    /**
     * 根据一级分区id查询 下级  二/三级分区id
     * @param agencyId
     * @return
     */
   public List<Long> getSubordinateAgencyIds(Long agencyId){
        return baseMapper.getSubordinateAgencyIds(agencyId);
    }

    /**
     * 修改机构，判断 isEditName 修改下级机构的 parentName
     * @param entity
     * @param isEditName
     * @return
     */
    @Transactional
    public boolean updateById(IotAgency entity,boolean isEditName){
        boolean result = retBool(baseMapper.updateById(entity));
        if(isEditName){// 机构名称修改
            if(entity.getLevel()==4){// 修改水泵房名称,
                // 修改名称需同步修改水泵组的 水泵房名称
                IotWaterPumpGroup editWaterPumpGroup=new IotWaterPumpGroup();
                editWaterPumpGroup.setParentName(entity.getName());
                waterPumpGroupMapper.update(editWaterPumpGroup,new EntityWrapper<IotWaterPumpGroup>().eq("house_id",entity.getId()));
            }
            if(entity.getLevel()==3){//修改小区名称,
                //修改名称时 同步修改下级机构 的 上级机构名称
                IotAgency editAgency=new IotAgency();
                editAgency.setParentName(entity.getName());
                baseMapper.update(editAgency,new EntityWrapper<IotAgency>().eq("parent_id",entity.getId()));
                //修改名称时 同步修改 水泵组 的 社区名称
                IotWaterPumpGroup editWaterPumpGroup=new IotWaterPumpGroup();
                editWaterPumpGroup.setCommunityName(entity.getName());
                waterPumpGroupMapper.update(editWaterPumpGroup,new EntityWrapper<IotWaterPumpGroup>().eq("community_id",entity.getId()));
            }
            if(entity.getLevel()==2){//修改物业名称
                IotAgency editAgency=new IotAgency();
                editAgency.setParentName(entity.getName());
                baseMapper.update(editAgency,new EntityWrapper<IotAgency>().eq("parent_id",entity.getId()));
            }
        }
        return result;
    }
    /**
     * 查询 二供机构 管理模块 分页栏数据
     * @param page   分页对象
     * @param wrapper
     * @param map  查询过滤条件 (orgIds- 机构id  ,groupIds -水泵组id)
     * @return
     */
    public  Page<Map<String,Object>> selectPage(Page<Map<String,Object>> page, Wrapper<Map<String,Object>> wrapper, Map<String,String> map){
        SqlHelper.fillWrapper(page, wrapper);
//        page.setRecords( baseMapper.getAgencyManagePageData(page,wrapper,map) );
        StringBuffer sqlSelect = new StringBuffer(400);
        sqlSelect.append("SELECT t1.id,t1.level,t1.name,t1.code,IFNULL(t1.linkPhone,\"\") as linkPhone,IFNULL(t1.linkName,\"\") as linkName,IFNULL(t1.agencyAddress,\"\") as agencyAddress,t1.companyCode from (");
        sqlSelect.append(" ( SELECT agency_id as id,agency_level as level,agency_name as name,agency_code as code,agency_address as agencyAddress,manage_name as linkName,manage_phone as linkPhone,company_code as companyCode from iot_agency");

        if(null != map.get("orgIds")){
            sqlSelect.append(" where agency_id in ( "+ map.get("orgIds")+")");
        }
        sqlSelect.append(")");// 查询 机构数据 的括号
        // 通过 unoin 联合查询 水泵组
        sqlSelect.append(" union ( SELECT group_id as id,5 as level,group_name as name,group_code as code,\"\" as agencyAddress,link_name as linkName,link_phone as linkPhone,company_code as companyCode from iot_water_pump_group");
        if(null != map.get("groupIds")){
            sqlSelect.append(" where group_id in ( "+ map.get("groupIds")+")");
        }
        sqlSelect.append(" )");// 查询 水泵组数据 的括号
        sqlSelect.append(" ) as t1 ");// 对应 from 的括号
        wrapper.setSqlSelect(sqlSelect.toString());
        page.setRecords( baseMapper.getAgencyManagePageData1(page,wrapper) );
        return page;
    }
    /**
     * 查询数据用于 机构数展示
     * @param wrapper
     * @return
     */
    public List<Map<String,Object>> selectMapList(Wrapper<IotAgency> wrapper){
        return baseMapper.selectMapList(wrapper);
    }

    /**
     * 删除 机构及其下级机构/水泵组
     * @param orgIds 机构id
     */
    @Transactional
    public  void delAgencyAndWaterPumpGroup(String orgIds){
        baseMapper.delAgencyByIds(orgIds);// 删除机构
        waterPumpGroupMapper.delWaterPumpGroupByHouseIds(orgIds);
    }

    /**
     * 查询电子地图 小区,水泵房  信息展示
     * @param param {level-(1小区,1水泵房) communityId-小区id  houseId-水泵房id}
     */
   public List<Map<String,Object>> selectAgencyMapInfoByLevel(Map<String,Object> param){
       if(param==null||param.get("level")==null){ return new ArrayList<Map<String,Object>>();}
        return baseMapper.selectAgencyMapInfoByLevel(param);
    }

    /**
     * 获取角色关联机构的 机构树
     * @return
     */
   public Map<String,Object> readRoleAgencyTree(Wrapper<IotAgency> agencyWp){
       List<Map<String,Object>> treeList = baseMapper.selectMapList(agencyWp);
       Map<String,Object> returnMap = new HashMap<String,Object>();
       returnMap.put("id",-1L);
       returnMap.put("name","系统");
       returnMap.put("code","system");
       returnMap.put("parentId",-2);
       returnMap.put("level",1);
       returnMap.put("checked",0);
       returnMap.put("opened",1);
       List<Map<String,Object>> treeChildrenList = agencyFactorTree(treeList,0,1);
       returnMap.put("children",treeChildrenList);
       return returnMap;
    }

    /**
     * 关联删除
     * 水泵组
     * iot_alarm_record 报警记录表 group_id
     * iot_card_recharge 充值卡表  group_id
     * iot_card_recharge_historical_records 充值记录表  group_id
     * iot_repair_declare 设备保修表 group_id
     * iot_repair_maintenance 设备维修表
     * 同时 删除 百度天工
     *
     * 水泵房
     * iot_eq_camera 摄像头
     * @param id
     * @param level
     * @return
     */
    @Override
    @Transactional
    public void joinDelete(Long id, Integer level) {
        if(level==5){//  水泵组
            waterPumpGroupMapper.joinDelWaterPumpGroupById(id+"");
        }
        if(level != 5){// 物业,小区,水泵房
            if(level==4){//水泵房
                baseMapper.delAgencyByIds(id+"");// 删除机构
                //删除 水泵组
                waterPumpGroupMapper.joinDelWaterPumpGroupByHouseIds(id+"");
                //删除 水泵房 摄像头
              R r =  iotEqCameraService.deleteByIotEqCameraId(id+"");
              if(r.get("code")==null||(Integer)r.get("code")!=200){
                    throw new RRException("删除关联摄像头失败",400);
              }
            }
            if(level!=4){// 物业,小区
                List<Long> orgIds = getSubordinateAgencyIds(id);//获取所有机构id
                if(orgIds==null){orgIds = new ArrayList<Long>();}
                StringBuffer orgIdsStr = new StringBuffer("");
                orgIdsStr.append(id);
                for(int x=0,length =orgIds.size();x<length;x++ ){
                    orgIdsStr.append(",").append(orgIds.get(x));
                }
                String delOrgIds = orgIdsStr.toString();
                baseMapper.delAgencyByIds(delOrgIds);// 删除机构
                //删除 水泵组
                waterPumpGroupMapper.joinDelWaterPumpGroupByHouseIds(delOrgIds);
                //删除 水泵房关联摄像头
                R r =  iotEqCameraService.deleteByIotEqCameraId(delOrgIds);
                if(r.get("code")==null||(Integer)r.get("code")!=200){
                    throw new RRException("删除关联摄像头失败",400);
                }
            }
        }
    }

    /**
     * 将List转换为树结构
     * @param tree
     * @param checked 是否默认选中(0-未选中(默认),1-选中)
     * @param opened 是否默认展开(0-未展开(默认),1-展开)
     * @return
     */
    public List<Map<String,Object>> agencyFactorTree(List<Map<String,Object>> tree,Integer checked,Integer opened){
        try {
            List t_list = new ArrayList();
            if (tree != null) {
                Map<Long,Map<String,Object>> map = new HashMap<Long,Map<String,Object>>();
                for (Map<String,Object> org : tree) {
                    org.put("checked",checked);
                    org.put("opened",opened);
                    map.put((Long)org.get("id"), org);// 为了 可以根据id获取对象
                }
                for (Long o : map.keySet()) {//遍历map的key值-id
                    Long id = (Long) o;// 获取 id值
                    Map<String,Object> obj = map.get(id);// 得到对象
                    Long parentId = (Long)obj.get("parentId");// 获取 parentId值
                    if(id==null || id.longValue()==-1L){// 最顶级
                        t_list.add(obj);
//                        map.put(cId,obj);
                        continue;
                    }
                    Map<String,Object> parentObj = map.get(parentId);//得到推荐人对象
                    if(parentObj == null){// 最顶级
                        t_list.add(obj);
//                        map.put(cId,obj);
                        continue;
                    }
                    List list =(List) parentObj.get("children");
                    if (CollectionUtils.isEmpty(list)) {
                        list = new ArrayList();
                    }
                    list.add(obj);
                    parentObj.put("children",list);
                    map.put(parentId,parentObj);
                }
            }
            return t_list;
        }catch(Exception ex){
            ex.printStackTrace();
            return null;
        }
    }

  public   List<Long> selectByAgencyIdS(Map<String,Object> param){
        return  baseMapper.selectByAgencyIdS(param);
    }
}
